<?php


namespace app\admin\logic;

use app\admin\error\Admin as AdminError;

/**
 * 会员逻辑
 */
class AdminLogic extends AdminBase
{

    /**
     * 获取会员信息
     */
    public static function getAdminInfo($data = [], $field = true)
    {

        $where['id'] = $data;

        $info = self::model('Admin')->getInfo($where, '*');

        $info['leader_nickname'] = self::model('Admin')->getOneValue(['id' => $info['leader_id']], 'nickname');

        return $info;
    }

    /**
     * 获取会员列表
     */
    public static function getAdminList($where = [], $field = 'm.*,b.nickname as leader_nickname,aga.group_id,ag.name as groupname', $order = '', $paginate = DB_LIST_ROWS)
    {

        $result = [];
        $data = self::model('Admin')->adminGetList($where, $field, $order, $paginate);
        if (!empty($data)) {

            foreach ($data as $key => $value) {
                if(empty($result[$value['id']])){

                    $result[$value['id']]['id'] = $value['id'];
                    $result[$value['id']]['nickname'] = $value['nickname'];
                    $result[$value['id']]['username'] = $value['username'];
                    $result[$value['id']]['email'] = $value['email'];
                    $result[$value['id']]['mobile'] = $value['mobile'];
                    $result[$value['id']]['create_time'] = $value['create_time'];
                    $result[$value['id']]['status'] = $value['status'];
                    $result[$value['id']]['leader_nickname'] = $value['leader_nickname'];
                    !empty($value['group_id']) ? $result[$value['id']]['group_id'][] = $value['group_id'] : $result[$value['id']]['group_id'] = [] ;
                    !empty($value['groupname']) ? $result[$value['id']]['groupname'][] = $value['groupname'] : $result[$value['id']]['groupname'] = [];
                }else{
                   !empty($value['group_id']) && $result[$value['id']]['group_id'][] = $value['group_id'];
                   !empty($value['groupname']) && $result[$value['id']]['groupname'][] = $value['groupname'];
                }
            }
            $result =array_values($result);
        }
        return $result;
    }

    /**
     * 获取会员列表搜索条件
     */
    public static function getWhere($data = [])
    {
        $adminInfo = Oauth::$userInfo;
        $where = [];
        !empty($data['search_data']) && $where[] = ['m.nickname|m.username|m.email|m.mobile', 'like', '%' . $data['search_data'] . '%'];

        if (0 == 0) {

            $admin = session('admin_info');

            if ($admin['is_share_member']) {

                $ids = self::getInheritAdminIds($adminInfo['id']);

                $ids[] = $admin['id'];

                $where[] = ['m.leader_id', 'in', $ids];

            } else {

                $where[] = ['m.leader_id', '=', $adminInfo['id']];
            }
        }

        return $where;
    }

    /**
     * 获取存在继承关系的会员ids
     */
    public function getInheritAdminIds($id = 0, $data = [])
    {


        $admin_id = self::model('Admin')->getValue(['id' => $id, 'is_share_member' => 1], 'leader_id');

        if (empty($admin_id)) {

            return $data;
        } else {

            $data[] = $admin_id;

            return $this->getInheritAdminIds($admin_id, $data);
        }
    }

//

    /**
     * 会员添加
     */
    public static function adminAdd($data = [])
    {
        $admin = Oauth::$userInfo;
        self::paramSceneCheck(self::validate("admin"), "edit", $data);


        $data['nickname'] = $data['username'];
        $data['password'] = data_md5_key($data['password']);
        $data['leader_id'] = $admin['id'];
        $data['is_inside'] = DATA_NORMAL;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $dataArray = [];

        $groupArray = $data['group_id'];
        unset($data['group_id']);
        $result = self::model('Admin')->getAddId($data);


        if (!empty($groupArray)) {

            foreach ($groupArray as $key => $value) {
                $dataArray[] = ['admin_id' => $result, 'group_id' => $value, 'create_time' => time(), 'update_time' => time()];
            }

            self::model('AuthGroupAccess')->addList($dataArray);
        }


        return $result ? $result : self::adminError(AdminError::$addError);
    }

    /**
     * 会员编辑
     */
    public static function adminEdit($param = [])
    {
        self::paramSceneCheck(self::validate("admin"), "edit", $param);

        if (!empty($param['username'])) {
            $info_where[] = ['username', '=', $param['username']];
            !empty($param['id']) && $info_where[] = ['id', '<>', $param['id']];
            $info = self::model('Admin')->getAdminInfo($info_where, '*');
            $info && self::adminError(AdminError::$AdminNameRepetition);
        }
        $dataArray = [];

        $groupArray = $param['group_id'];
        unset($param['group_id']);
        //数据

        $keys = ['nickname', 'username', 'email', 'mobile'];
        foreach ($keys as $key) isset($param[$key]) && $data[$key] = $param[$key];
        unset($data['password']);
        empty($data) && self::adminError(AdminError::$noChange);
        !empty($data['password']) && $data['password'] = data_md5_key($data['password']);
        $where['id'] = $param['id'];
        $data['update_time'] = time();

//        _p($data);
        self::model('Admin')->updateAdminInfo($data, $where ?? []);

        if (!empty($groupArray)) {

            self::model('AuthGroupAccess')->deleteData( ['admin_id' =>  $where['id']]);
            foreach ($groupArray as $key => $value) {
                $dataArray[] = ['admin_id' =>  $where['id'], 'group_id' => $value, 'create_time' => time(), 'update_time' => time()];
            }

            self::model('AuthGroupAccess')->addList($dataArray);
        }

        return ['data' => true];


    }
//
//    /**
//     * 修改密码
//     */
//    public function editPassword($data = [])
//    {
//
//        $validate_result = $this->validateAdmin->scene('password')->check($data);
//
//        if (!$validate_result) {
//
//            return [RESULT_ERROR, $this->validateAdmin->getError()];
//        }
//
//        $admin = $this->getAdminInfo(['id' => $data['id']]);
//
//        if (data_md5_key($data['old_password']) != $admin['password']) {
//
//            return [RESULT_ERROR, '旧密码输入不正确'];
//        }
//
//        $data['id'] = ADMIN_ID;
//
//        $url = url('index/index');
//
//        $result = $this->modelAdmin->setInfo($data);
//
//        $result && action_log('编辑', '会员密码修改，id：' . $data['id']);
//
//        return $result ? [RESULT_SUCCESS, '密码修改成功', $url] : [RESULT_ERROR, $this->modelAdmin->getError()];
//    }
//
//    /**
//     * 设置会员信息
//     */
//    public function setAdminValue($where = [], $field = '', $value = '')
//    {
//
//        return $this->modelAdmin->setFieldValue($where, $field, $value);
//    }

    /**
     * 会员删除
     */
    public static function adminDel($data = [])
    {
        $admin = Oauth::$userInfo;

        $where['id'] = $data['id'];
        if (SYS_ADMINISTRATOR_ID == $where['id'] || $admin['id'] == $where['id']) {

            self::adminError(AdminError::$insufficientPrivileges);
        }

        $result = self::model('Admin')->getOneValue($where, DATA_STATUS_NAME, DATA_DELETE);


        return $result ? $result : self::adminError(AdminError::$deleteError);
    }
}
